﻿using System;
using System.Collections.Generic;
using System.Linq;
using yiCommerce.Core;
using yiCommerce.Core.Domain.Orders;
using yiCommerce.Core.Domain.Payments;

namespace yiCommerce.Service.Payments
{
    public class PaymentService:IPaymentService
    {
        public ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var paymentMethod = LoadPaymentMethodBySystemName(processPaymentRequest.PaymentMethodSystemName);
            if (paymentMethod == null)
                throw new Exception("Payment method couldn't be loaded");
            return paymentMethod.ProcessPayment(processPaymentRequest);

        }

        public IList<IPaymentMethod> LoadActivePaymentMethods()
        {
            return new List<IPaymentMethod>()
                {
                    EngineContext.Current.ResolveNamed<IPaymentMethod>("AlipayPaymentMethod"),
                    EngineContext.Current.ResolveNamed<IPaymentMethod>("DummyPaymentMethod")
                };
        }

        public IPaymentMethod LoadPaymentMethodBySystemName(string paymentmethod)
        {
            var methods = this.LoadActivePaymentMethods().Where(t => t.SystemName == paymentmethod).FirstOrDefault();

            return methods;
        }

        public void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
        {
            var paymentMethod = LoadPaymentMethodBySystemName(postProcessPaymentRequest.PaymentMethodSystemName);
            if (paymentMethod == null)
                throw new Exception("Payment method couldn't be loaded");
            paymentMethod.PostProcessPayment(postProcessPaymentRequest);
        }

        public bool CanRePostProcessPayment(Order order)
        {
            var paymentMethod = LoadPaymentMethodBySystemName(order.PaymentMethodSystemName);
            if (paymentMethod == null)
                throw new Exception("Payment method couldn't be loaded");
            return paymentMethod.CanRePostProcessPayment();
        }
    }
}